import { Edge } from '@antv/x6';
import { Drawer } from 'antd';

import RightArrowIcon from '@/assets/icons/right-arrow.svg';
import { colors } from '@/config/theme';
import { TNodeType } from '@/constants/config';
import { useCurrentEdge } from '@/hooks/useCurrentEdge';
import { useGraph } from '@/hooks/useGraph';
import { useDictStore } from '@/store/dict';
import { formatConditions, setEdgeLabel } from '@/utils/graph';

import { BaseNodeContent } from '../BaseNode';
import { CriteriaItem, Rules } from '../Rules';

export const EdgeDrawer = memo(() => {
  const { activeEdgeId, setActiveEdgeId, parentPrivateVariables, parentPublicVariables, setDataForEdge, getDataForEdge } =
    useCurrentEdge();
  const { graph } = useGraph();
  const [rules, setRules] = useState({} as CriteriaItem);
  const { systemVars } = useDictStore();

  const closeEdge = () => {
    const criteria = getDataForEdge()?.criteria;
    const label = formatConditions(criteria!);
    const node = graph?.getCellById(activeEdgeId!) as Edge;
    setEdgeLabel(node, label, false);
    setTimeout(() => {
      setActiveEdgeId('');
    });
  };

  const edgeOfNodes = useMemo(() => {
    const node = graph?.getEdges().find((edge) => edge.id === activeEdgeId);
    const sourceShape = node?.getSourceCell()?.shape;
    const targetShape = node?.getTargetCell()?.shape;
    return {
      sourceShape,
      targetShape
    };
  }, [activeEdgeId, graph]);

  useEffect(() => {
    setRules(getDataForEdge()?.criteria || ({} as CriteriaItem));
  }, [getDataForEdge]);

  const variables = parentPrivateVariables.concat(parentPublicVariables);
  const variablesWithSystem = variables.concat(systemVars);

  return (
    <Drawer
      destroyOnClose
      width={700}
      placement="bottom"
      open={!!activeEdgeId}
      title={
        <div className="flex gap-20 items-center">
          <BaseNodeContent nodeType={edgeOfNodes?.sourceShape as TNodeType} />
          <RightArrowIcon color={colors.gray[300]} width={18} height={18} />
          <BaseNodeContent nodeType={edgeOfNodes?.targetShape as TNodeType} />
        </div>
      }
      onClose={closeEdge}>
      <div className="pt-12 max-w-1200 mx-auto">
        <Rules
          leftVariables={variablesWithSystem}
          rightVariables={variables}
          value={rules}
          onChange={(criteria) => {
            setRules(criteria);
            setDataForEdge({ criteria: criteria });
          }}
        />
      </div>
    </Drawer>
  );
});
